/**
 * Created by Dalyn on 2017/5/12.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import ReactKey from "../../../../util/ReactKey";
import GetQiNiuToken from "../mutation/GetQiNiuTokenMutation"  //上传图片获取token
import DelQiniuFileMutation from "../mutation/DelQiniuFileMutation" // 删除图片
import SaveProOthersDetailMutation from '../mutation/otherRequireMutation/SaveProOthersDetailMutation';
import {Header,ViewImgList} from'../components/PackStep_Header';
import AddImgModal from "../components/AddImgModal";  //上传图片
import FileUpData from '../components/FileUpDataPro'  //上传附件

import {Button} from 'fly';

import {message,Modal,Input} from 'antd';
const confirm = Modal.confirm;
import "../css/otherRequirements.css";

import Config from "../../../../util/Config"

/*
 * 工艺要求  展示层  ui纯UI无状态组件
 * */
export default class OtherRequirementsItem extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
            token:this.props.token,
            previewVisible:false,  //图片预览
            previewImage: '',
            item:this.props.item,
            othersIds:"",
            /*title:this.props.item.tltle,
            content:this.props.item.content,
            imgJSON:this.props.item.imgJSON,
            fileJSON:this.props.item.fileJSON,*/
        };
        this.itemProps =this.props.item;
        this.FixedImgSrc = Config.qiuniu;
        this.imgDeleteKey = [];
        this.isSave = true;
        this.pdId = this.props.pdId;
        this.addFile = this.addFile.bind(this);
        this.addImg = this.addImg.bind(this);
        this.addFileImg = this.addFileImg.bind(this);

        this.save = this.save.bind(this);

        this.handleCancel = this.handleCancel.bind(this);

        this.addFileItem = this.addFileItem.bind(this);
    }

    //  验证格式需要通过obj传递到另一个组件调用，必须要在当前proto原型上，不可添加到自由属性.
    accept = ".jpg,.png,.gif,.jpeg,.bmp";
    fileAccept = ".pdf,.xlsx,.xls,.docx,.doc";

    componentWillMount() {
        /*let aaa = [1,2,3];
        let ddd = aaa.filter((v,i)=>{
            return v != 2
        });*/
        // console.log(ddd);
        this.getQiniuToken();
    }
    //获取上传图片所需的token
    getQiniuToken(){
        Relay.Store.commitUpdate(
            new GetQiNiuToken({}), {
                onSuccess: (res) => {
                    let errorCode = res.getQiNiuToken.getQiNiuToken.errorCode;
                    if(errorCode==0){
                        let qiniutoken = res.getQiNiuToken.getQiNiuToken.qiniutoken;
                        this.setState({
                            token:qiniutoken
                        });
                    }
                }
            }
        );
    }

    /*点击保存*/
    save(index){
        let itemSelf = this.state.item;
        let req = /^(\s)*$/g;

        if(req.test(itemSelf.title)||itemSelf.title.length <= 0){
            message.warning("标题不能为空");
            return
        }
        const F = JSON.parse(itemSelf.fileJSON);;

        // 筛选文是否为 uploading
        for(let key in F){
            if(F[key].status === "uploading"){
                message.info("文件正在上传中");
                this.setState({dis_btn:false});
                return false
            }
        }

        if(this.isSave){
            this.isSave = false;
            let itemStr = JSON.stringify(this.state.item);
            let itemPropsStr = JSON.stringify(this.itemProps);

            /*判断是否修改*/
            if(itemStr == itemPropsStr){
                Relay.Store.commitUpdate(
                    new SaveProOthersDetailMutation({
                        pdId:this.pdId,
                        othersDetail:itemStr,
                    }),
                    {
                        onFailure: (err) => {
                            message.error("网络请求失败")
                        },
                        onSuccess: (res)=> {
                            let errorCode = res.saveProOthersDetail.responseData.errorCode;
                            if(errorCode == 0){
                                let proOthersDetailModel = res.saveProOthersDetail.responseData.proOthersDetailModel;
                                this.props._saveItem(index,proOthersDetailModel.othersId);

                                setTimeout(() => {
                                    this.isSave = true;
                                    message.success("保存成功")
                                },300)
                            }else {
                                if (errorCode == 500){
                                    message.error('服务器错误,请联系系统管理员');
                                }
                            }
                        }
                    }
                );
            }
            if(this.imgDeleteKey.length >0){
                /*删除七牛*/
                Relay.Store.commitUpdate(
                    new DelQiniuFileMutation({
                        fileKey: this.imgDeleteKey.join(",")
                    }),
                    {
                        onFailure: () => {
                        },
                        onSuccess: (response) => {
                            let errorCode = response.delQiniuFile.delQiniuFile.errorCode;
                            if (errorCode == 0) {
                                /* //过渡动画
                                 itemSelf.imgJSON[index].file.__transClass = "leave";
                                 // item.file.__transClass = "leave";
                                 // itemSelf.imgJSON[index] = item;
                                 this.setState({item: itemSelf});

                                 setTimeout(() => {
                                 itemSelf.imgJSON.splice(index, 1);
                                 this.setState({
                                 item: itemSelf
                                 }, () => {
                                 loading()
                                 })
                                 }, 300)*/

                            } else {
                                /*loading();
                                 message.error("出现问题，移除失败，请重试")*/
                            }
                        }
                    }
                )
            }
        }
    }
    /*点击删除item*/
    showConfirm(index,othersIds,pdId) {
        confirm({
            title: '提示',
            content: '确定要删除此条么？',
            onOk(){
                if(othersIds){
                    Relay.Store.commitUpdate(
                        new SaveProOthersDetailMutation({
                            pdId:pdId,
                            othersIds: othersIds,
                        }),
                        {
                            onFailure: (err) => {
                                message.error('加载失败,请检查网络连接');
                            },
                            onSuccess: (res)=> {
                                setTimeout(()=>{
                                    this.props._deleteRequire(index);
                                    message.success("删除成功");
                                }, 300);
                            }
                        }
                    )
                }else {
                    setTimeout(()=>{
                        this.props._deleteRequire(index);
                        message.success("删除成功");
                    }, 300);
                }
            },
            onCancel() {},
        });
    }
    delete(index,othersIds){
        if(othersIds){
            Relay.Store.commitUpdate(
                new SaveProOthersDetailMutation({
                    pdId:this.pdId,
                    othersIds: othersIds,
                }),
                {
                    onFailure: (err) => {
                        message.error('删除失败,请检查网络连接');
                    },
                    onSuccess: (res)=> {
                        setTimeout(()=>{
                            this.props._deleteRequire(index);
                            message.success("删除成功");
                        }, 300);
                    }
                }
            )
        }else {
            setTimeout(()=>{
                this.props._deleteRequire(index);
                message.success("删除成功");
            }, 300);
        }
    }
    addFile(){

    }

    addImg(){
        let itemSelf = this.state.item;
        let imgJSON = JSON.parse(itemSelf.imgJSON);
        if(imgJSON.length>=10){
            message.warning("图片最多允许上传10个");
            return false;
        }
        this.refs.addFileImgModal.setState({
            visible:true
        })
    }
    /*标题编辑*/
    handleTitleChange(type,index,e){
        let itemSelf = this.state.item;
        let text = e.target.value;
        if(text.length>50)return;
        this.refs[index+type].value = text;
        itemSelf["title"] = text;
        this.setState({
            item:itemSelf,
        })
    }
    /*内容编辑*/
    handleTextChange(type,index,e){
        let itemSelf = this.state.item;
        let text = e.target.value;
        /*限制？？？*/
        if(text.length>2000)return;
        this.refs[index+type].value = text;
        itemSelf["content"] = text;
        this.setState({
            item:itemSelf,
        })
    }

    //上传图片配置
    uploadPlugin = {
        className:"packagSteps_updata",
        action:"http://up-z2.qiniu.com",
        beforeUpload:this.beforeUpload,
        listType:"picture-card",
        accept:this.accept,
    };
    // 上传文件配置
    fileUploadPlugin = {
        action: 'http://up-z2.qiniu.com',
        beforeUpload:this.fileBeforeload.bind(this),
        accept:this.fileAccept,
    };

    /*上传图片之前验证*/
    beforeUpload(file){
        const MaxSize = 8;  //最大限度 8M;
        // 图片格式
        if(file.type !== "image/jpeg" && file.type !== "image/jpg" && file.type !== "image/png" && file.type !== "image/gif" && file.type !== "image/bmp"){
            message.error("图片格式错误");
            return false;
        }

        // 图片大小
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("图片大小超过限制");
            return false;
        }

        // 限制图标张数
        /*if(this.state.item.imgJSON >= 10){
            message.info("超过限制，图片做多只可上传10张");
            return false;
        }*/
    }
    /*上传附件点击事件*/
    handleClickSelf(){
        let itemSelf = this.state.item;
        let fileJSON = JSON.parse(itemSelf.fileJSON);
        if(fileJSON.length>=5){
            message.warning("附件最多允许上传5个");
            return;
        }
    }
    //附件上传之前验证
    fileBeforeload(file){
        let itemSelf = this.state.item;
        let fileJSON = JSON.parse(itemSelf.fileJSON);
        if(fileJSON.length>5){
            message.warning("附件最多允许上传5个");
            return;
        }
        const MaxSize = 10;  //最大限度 10M;
        if( file.size / 1024 / 1024 > MaxSize ){
            message.error("文件大小超过限制");
            return false;
        }

        // 当前已经上传的length
        // if(this.state.fileUpdataList.length > 5){ message.info("文件最多可上传10个"); return false; }

        // 暂时抛弃
        // if(  file.type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
        //     file.type !== "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
        // ){
        //     message.error("文件格式错误，请查看上传规则");
        //     return false;
        // }
    }
    //上传图片成功回调
    addFileImg({file,text}){
        let itemSelf = this.state.item;
        let imgJSON = JSON.parse(itemSelf.imgJSON);
        if(imgJSON.length < 10) {
            if (file) {
                imgJSON.push({file,text});
                itemSelf.imgJSON = JSON.stringify(imgJSON);
                this.setState({
                    item: itemSelf,
                })
            }
        }else{
            message.error("最多只可上传10张");
        }
    }
    // 预览图片
    handlePreview = (item,index) => {
        this.setState({
            previewVisible:true,
            previewImage:this.FixedImgSrc + item.file.response.key,
        })
    };
    // 删除图片
    picRemove(item,index){
        let itemSelf = this.state.item;
        //下列固定为0，因为list最多只能上传一个，固0
        const name = item.file.response.key;
        const loading = message.loading("正在移除当前图片");
        /*存入待删除数组*/
        this.imgDeleteKey.push(name);
        /*先只做本地删除-点击保存*/
        let imgJSON = JSON.parse(itemSelf.imgJSON);
        imgJSON[index].file.__transClass = "leave";
        itemSelf.imgJSON = JSON.stringify(imgJSON);
        this.setState({ item:itemSelf});
        setTimeout(()=>{
            imgJSON.splice(index,1);
            itemSelf.imgJSON = JSON.stringify(imgJSON);
            this.setState({
                item:itemSelf
            },()=>{loading()})
        },300);
    }
    // 预览图片关闭
    handleCancel = ()=>{
        this.setState({
            previewVisible:false,
        })
        // 优化用户体验，延时一秒清空图片
        setTimeout(()=>{
            this.setState({
                previewImage:""
            })
        },700);
    };
    /*上传文件*/
    addFileItem(file){
        let itemSelf = this.state.item;
        // let fileJSON = JSON.parse(itemSelf.fileJSON);
        // fileJSON.push(file);
        // itemSelf.fileJSON = JSON.stringify(file);
        itemSelf.fileJSON = JSON.stringify(file);
        this.setState({
            item:itemSelf,
        })
    }

    render(){
        const {token,previewVisible,previewImage} = this.state;
        let {title,content,fileJSON,imgJSON,othersId} = this.state.item;
        let index = this.props.index;
        fileJSON ? fileJSON = JSON.parse(fileJSON) : [];
        imgJSON ? imgJSON = JSON.parse(imgJSON) : [];
        return (
            <div className="poduction_otherReq_item poduction_otherRequ_edit">
                <div className="poduction_otherRequ_header_text">
                    <div>
                        <Input type="textarea" ref={index+"title"}
                               className="poduction_otherRequ_textInput_title"
                               rows={1}
                               value={title} maxlength="5"
                               placeholder="请填写标题"
                               onChange={this.handleTitleChange.bind(this,"title",index)}
                        />
                        <Button className="echOherRequ_item_button" onClick={this.save.bind(this,index)}> 保存 </Button>
                    </div>
                    <div>
                        <Input type="textarea" ref={index+"content"}
                               className="poduction_otherRequ_textInput"
                               rows={6}
                               value={content} maxlength="2000"
                               placeholder="请填写详细要求"
                               onChange={this.handleTextChange.bind(this,"content",index)}
                        />
                        <Button className="echOherRequ_item_button" onClick={this.delete.bind(this,index,othersId,this.pdId)}> 删除 </Button>
                    </div>
                </div>

                <div className="poduction_otherRequ_hea_btn">
                    <div>
                        <Header
                            className="_left"
                            No1={this.addImg}
                        />
                        {/*上传文件*/}
                        <FileUpData
                            className="poduction_otherRequ_updataFile"
                            filePlugin={this.fileUploadPlugin}
                            fileList={fileJSON}
                            callBack={this.addFileItem}   //回调，第一个参数为file,第二个参数为本地name
                            token={token}
                            isShowTrigger={fileJSON.length < 5}
                            handleClickSelf={this.handleClickSelf.bind(this)}
                        />
                    </div>
                    <div>
                        {
                            imgJSON&&imgJSON.length !== 0 && imgJSON.map((item,index)=>
                                <ViewImgList
                                    key={item.file.uid}
                                    imgSrc={`${this.FixedImgSrc + item.file.response.key}`}
                                    imgName={item.file.name}
                                    handlePreview={(e)=>this.handlePreview(item,index)}
                                    handleRemove={(e)=>this.picRemove(item,index)}
                                    textValue={item.text}
                                    transClass={item.file.__transClass}   //过渡动画类，中途插入
                                />
                            )
                        }
                    </div>
                </div>
                {/*添加上传图片*/}
                <AddImgModal
                    uploadPlugin = {this.uploadPlugin}
                    ref="addFileImgModal"
                    token={token}   // 上传图片时，必须的token，(此token异步返回)
                    addFileImg={this.addFileImg}   //上传成功的回调，第一个参数的第一个属性为返回的fill,第二个属性为text描述
                    //  text 描述 props配置信息
                    TextProps={{  className:"packagSteps_AddImgModal_textArea",
                        rows:3,
                        placeholder:"请输入描述信息",
                        maxlength:50
                    }}
                    limit={{width:500,height:500}} //最小宽高限制参数
                />

                {/*预览图片*/}
                <Modal className="production_preview" visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        )
    }
}